/**
 * Created by tanbingqin on 2019/11/28.
 */
import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import AdvancedTable from 'components/advanced-table'
const { SimpleTable } = AdvancedTable;
import { Button, Input, Tabs, Spin, Alert, Popconfirm, message, Icon, Modal, Form, Select, Row, Col } from 'antd'
const Search = Input.Search;
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const Option = Select.Option;
import menuRoute from 'routes/menuRoute'
import debounce from 'lodash.debounce'
import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import 'styles/setting/agency-setting/agency-setting.scss'
import moment from 'moment'
import errorMessage from 'share/errorMessage';

class AgencySettingV2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tab: 'apply',
      searchForm: [
        {
          id: 'companyOIDs',
          label: messages('request-3.key24')/*公司*/,
          component: 'Chooser',
          props: {
            labelKey: 'name',
            valueKey: 'id',
            type: 'priority_company'
          },
          dataIndex: 'companyName',
          parser: value => ({
            companyIds: value ? value.map(item => item.id) : null
          })
        }
      ],
      columns: [
        {title: messages('request-3.key69')/*被代理人*/, dataIndex: 'userName', render: (name, record) => {
          return record.status === 1003 ?  //status:1003 已离职
            <div><span className='default-color-font'>{messages('request-3.key14')/*离职*/}</span> - {name}</div> : name;
        }},
        {title: messages('common.user.id')/*工号*/, dataIndex: 'emplyeeId'},
        {title: messages('request-3.key24')/*公司*/, dataIndex: 'companyName'},
        {title: messages('common.department')/*部门*/, dataIndex: 'departmentName'},
        {title: messages('request-3.key80')/*职务*/, dataIndex: 'dutyName', render: value => value || '-'},
        {
          title: messages('common.operation')/*操作*/,
          dataIndex: 'operate',
          width: '10%',
          render: (text,record) => (
            <span>
              <Popconfirm placement="topLeft" onConfirm={(e) => this.handleDelete(e, record)} title={messages('request-3.key12')/*你确认要删除？*/}>
                <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')/*删除*/}</a>
              </Popconfirm>
            </span>
          )
        }
      ],
      proxyVisible: false, //选被代理人的modal
      proxyData: [], //被代理人列表数据
      fetching: false,
      saveLoading: false, //新建被代理人的loading
      validateStatus: '', //被代理人校验的status
      validateMessage: '', //被代理人校验的message
    };
    this.handleSearch = debounce(this.handleSearch, 500);
    this.searchValue = debounce(this.searchValue, 250);
    this.appSetting = menuRoute.getRouteItem('sub-application','key');
    this.newAgency = menuRoute.getRouteItem('new-agency','key');    //新建代理
    this.agencyDetail = menuRoute.getRouteItem('agency-detail','key');    //代理详情
  }

  componentWillMount() {
    const { location } = this.props;
    this.setState({ tab: location.query.tab || 'apply' });
  }

  service = (page, pageSize, searchParams) => {
    const { tab, keyWords } = this.state;
    return agencyService.getAgencyList(tab === 'apply' ? 1 : 2, page, pageSize, keyWords, searchParams);
  };

  //tab切换
  handleTabChange = (tab) => {
    this.setState({ tab }, () => {
      this.simpleTableRef.getList(true, 1);
    });
  };

  //搜索 姓名／工号
  handleSearch= (value) => {
    this.setState({keyWords: value}, () => {
      this.simpleTableRef.getList(true, 1);
    });
  };

  toGoAPPSetting = () => {
    let url = this.appSetting.url;
    if (window.ISIE9) {
      url = `#${url}`;
    }
    window.open(url);
  };

  handleNew = () => {
    this.setState({
      proxyVisible: true
    });
  };

  handleRowClick = (record) => {
    const { tab } = this.state;
    this.context.router.push(this.agencyDetail.url.replace(':principalOID', record.principalOID) + `?tab=${tab}`);
  };

  handleDelete = (e, record) => {
    let params = {
      proxyOperationType: record.proxyOperationType,
      recordOID: record.recordOID
    };
    agencyService.deleteAgencyItem(params).then(res => {
      message.success(messages('common.delete.successful')/*删除成功*/);
      this.simpleTableRef.getList(true, 1);
    }).catch(() => {
      message.error(messages('common.operate.filed')/*操作失败*/);
    });
  };

  //选被代理人的modal
  closeProxyModal = () => {
    const { resetFields } = this.props.form;
    resetFields();
    this.setState({
      proxyVisible: false,
      proxyData: [],
      validateStatus: '', //被代理人校验的status
      validateMessage: '' //被代理人校验的message
    });
  };

  searchValue = (value) => {
    const { tab } = this.state;
    value && this.setState({
      fetching: true
    });
    let params = {
      page: 0,
      size: 1000,
      keyword: value
    };
    params.status = tab === 'apply' ? undefined : 'all'; //undefined为不传status参数，查出的为在职和待离职人员
    value && value.length && agencyService.getPersonByValueV2(params).then(res => {
      let resultData = [];
      let data = res.data;
      data.map(item => {
        item.text = `${item.fullName} - ${item.employeeID}`;
        //只支持工号和姓名搜索，手机和邮箱要去除
        if (item.text.toLowerCase().indexOf(value.toLowerCase()) > -1 || item.text.toUpperCase().indexOf(value.toUpperCase()) > -1) {
          resultData.push(item);
        }
      });
      this.setState({ proxyData: resultData, fetching: false });
    });
  };

  onBlur = () => {
    const { getFieldValue, setFieldsValue } = this.props.form;
    const { proxyData } = this.state;
    let isExist = false;
    let userOID = '';
    if (getFieldValue("principalInfo")) {
      let principalInfo = JSON.parse(getFieldValue("principalInfo"));
      userOID = principalInfo.userOID;
    }
    proxyData && proxyData.forEach(user => {
      if (user.userOID === userOID) {
        isExist = true;
      }
    });
    if (!isExist) {
      setFieldsValue({
        principalInfo: undefined
      });
      this.setState({validateStatus: 'error', validateMessage: messages('common.select')/*请选择*/});
    }
  };

  //保存被代理人
  handleNewProxy = () => {
    const { tab, validateStatus } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err && validateStatus !== 'error') {
        let principalInfo = JSON.parse(values.principalInfo);
        principalInfo.billProxyRuleDTOs = [];
        principalInfo.enabled = false;
        principalInfo.principalOID = principalInfo.userOID;
        principalInfo.proxyOperationType = tab === 'apply' ? 1 : 2; //proxyOperationType：1（代理制单）、2（代理审批）
        this.setState({saveLoading: true});
        agencyService.newAgency(principalInfo).then(res => {
          this.setState({ saveLoading: false });
          message.success(messages('common.create.success',{arg1: ''})/*{arg1} 新建成功*/);
          this.closeProxyModal();
          this.simpleTableRef.getList(true, 1);
        }).catch(e => {
          this.setState({saveLoading: false});
          message.error(`${messages('common.create.filed')/*新建失败*/}， ${e.response.data.message}`);
        });
      } else {
        if (!values.principalInfo) {
          this.setState({validateStatus: 'error', validateMessage: messages('common.select')/*请选择*/});
        }
      }
    });
  };

  handleChange = (value) => {
    this.validateValue(value);
  };

  //校验被代理人控件
  validateValue = (value) => {
    const { tab } = this.state;
    let errorMsg = '';
    if (value) {
      let principalInfo = JSON.parse(value);
      agencyService.getPersonStatusByOid(principalInfo.userOID, tab === 'apply' ? 1 : 2).then(res => {
        if (res.data) {
          errorMsg = messages('request-3.key81')/*此员工已存在被代理信息，请在列表中搜索该员工并编辑*/;
          this.setState({validateStatus: 'error'});
        } else {
          let leaveTime = moment(principalInfo.leavingDate).format('YYYY-MM-DD');
          if (principalInfo.status === 1002) {
            errorMsg = messages('request-3.key60',{arg1: leaveTime})/*该员工将于 {arg1} 离职*/ +
              `${tab === 'apply' ? messages('request-3.key61')/*，离职后此代理将自动禁用*/ : ''}`;
            this.setState({validateStatus: 'warning'});
          } else if (principalInfo.status === 1003) {
            errorMsg = messages('request-3.key62',{arg1: leaveTime})/*该员工已于 {arg1} 离职*/;
            this.setState({validateStatus: 'warning'});
          } else {
            errorMsg = '';
            this.setState({validateStatus: ''});
          }
        }
        this.setState({validateMessage: errorMsg});
      }).catch(err => {
        errorMessage(err.response);
        this.setState({validateStatus: ''});
      });
    } else {
      errorMsg = messages('common.select')/*请选择*/;
      this.setState({validateStatus: 'error', validateMessage: errorMsg});
    }
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { columns, searchForm, tab, proxyVisible, proxyData, fetching, saveLoading, validateStatus, validateMessage } = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 18}
    };
    let message = (
      <span>
        {messages('request-3.key82')/*APP端启用设置*/}：
        <a onClick={() => this.toGoAPPSetting()}>
          {messages('request-3.key83')/*点此前往*/}
          <Icon type="right" />
        </a>
        {messages('request-3.key84')/*至【模块显示设置-我的】页面设置*/}
      </span>
    );
    return(
      <div className="agency-setting full-height-page">
        <div style={{marginTop: 16, padding: '0 20px'}}>
          <Alert message={message} type="info" showIcon />
        </div>
        <Tabs activeKey={tab} onChange={this.handleTabChange}>
          <TabPane tab={messages('request-3.key85')/*代理制单*/} key="apply" />
          <TabPane tab={messages('request-3.key86')/*代理审批*/} key="approve" />
        </Tabs>
        <div style={{padding: '0 20px'}} className='font-description'>
          {tab === 'apply' && (
            <span>{messages('request-3.key87')/*设置说明：设置指定员工代理制单规则*/}</span>
          )}
          {tab === 'approve' && (
            <spa>{messages('request-3.key88')/*设置说明：设置指定员工代理审批规则*/}</spa>
          )}
        </div>
        <SimpleTable
          columns={columns}
          searchForm={searchForm}
          service={this.service}
          rowKey="recordOID"
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          onRef={ref => this.simpleTableRef = ref}
          tableName='proxy-setting-list'
          expandAll
        >
          <div className="table-header">
            <div className="table-header-buttons">
              <Button type="primary" onClick={this.handleNew}>
                {messages('common.create')/*新建*/}
              </Button>
              <Search
                placeholder={messages('request-3.key63')/*请输入姓名/工号*/}
                className="input-search"
                onChange={e => this.handleSearch(e.target.value)}
              />
            </div>
          </div>
        </SimpleTable>
        <Modal
          title={messages('request-3.key89')/*新建被代理人*/}
          visible={proxyVisible} onCancel={this.closeProxyModal}
          maskClosable={false}
          destroyOnClose
          footer={[
            <Button key="back" onClick={this.closeProxyModal}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="submit" type="primary" disabled={saveLoading} onClick={this.handleNewProxy}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          <div className="new-form">
            <Form>
              <FormItem
                {...formItemLayout}
                label={messages('request-3.key69')/*被代理人*/}
                style={{marginBottom: 4}}
                validateStatus={validateStatus}
                help={validateMessage}
                extra={tab === 'apply' ? messages('request-3.key70')/*需要他人帮助其填写、提交相应单据的人*/ : messages('request-3.key71')/*需要他人帮助其审批相应单据的人*/}
              >
                {getFieldDecorator('principalInfo', {
                  rules: [
                    {
                      required: true
                    }
                  ]})(
                  <Select
                    placeholder={messages('request-3.key63')/*请输入姓名/工号*/}
                    allowClear
                    showSearch
                    filterOption={false}
                    notFoundContent={fetching ? <Spin size="small" /> : messages('common.unmatched')/*无匹配结果*/}
                    onSearch={this.searchValue}
                    onBlur={this.onBlur}
                    onChange={this.handleChange}
                    getPopupContainer={triggerNode => triggerNode.parentNode}
                  >
                    {proxyData.map(d => <Option key={JSON.stringify(d)}>{d.text}</Option>)}
                  </Select>
                )}
              </FormItem>
            </Form>
          </div>
        </Modal>
      </div>
    )
  }
}

AgencySettingV2.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const wrappedAgencySettingV2 = Form.create()(AgencySettingV2);

export default connect(mapStateToProps)(wrappedAgencySettingV2);
